package com.dhgate.spu.analysis.stat;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhgate.spu.analysis.bean.Product;
import com.dhgate.spu.analysis.collector.ExtractCollector;
import com.dhgate.spu.analysis.consts.SpuStandardConsts;
import com.dhgate.spu.analysis.consts.SysConsts;
import com.dhgate.spu.analysis.dao.DAOFactory;
import com.dhgate.spu.analysis.init.InitDbConfig;
import com.dhgate.spu.analysis.util.StringUtil;
/**
 * 
 * @Description: 
 * @author  
 * @version 1.0
 * @create time 2014-3-28 下午4:58:44
 */
public class StatAttrValMain {
	private static final Logger logger = LoggerFactory.getLogger(StatAttrValMain.class);

	/**
	 * 
	 * @Description: TODO
	 *
	 * @author zhaowei
	 * @param args
	 * @throws Exception void
	 * @create time 2014-3-28 下午4:58:40
	 */
	public static void main(String[] args) throws Exception {
		if(args.length<1){
			throw new Exception("input prodlineid is null");
		}
		//初始化基本配置参数
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(SysConsts.CONST_PARAMXML_PATH));
		SysConsts.DAO_NAME = document.getRootElement().element("DAO").getTextTrim();

		//初始化数据来源
		DAOFactory.init();
		
		//读取数据库初始化配置
		InitDbConfig.init();
		
		System.out.println("============"+DAOFactory.getDAOInstance()+" ========"+DAOFactory.getDAOInstance().getAttrValMap("520703"));
		
		SpuStandardConsts.init();
		
		//统计
		statAttrVal(args[0]);

	}

	private static void statAttrVal(String prodLineId) throws Exception {
		    long startTime=System.currentTimeMillis();
			ExtractCollector extractCollector=new ExtractCollector();
		
			File file = new File("attrval_recommend_"+prodLineId+".txt");
			if(file.exists()){
				FileUtils.deleteQuietly(file);
			}
				String attrValIds = SpuStandardConsts.getAttrValIds(prodLineId);
			if(StringUtil.isEmpty(attrValIds)){
				logger.error("attrValIds is null prodlineId:"+prodLineId);
				throw new Exception("attrValIds is null prodlineId:"+prodLineId);
			}
			int num=0;
			for (String l2sid : SysConsts.MYSQL_TABLE_KEY_LIST) {	
				if(num>=1000) break;
				List<Product> pList = DAOFactory.getDAOInstance().getProducts(l2sid, prodLineId, attrValIds);
				for (Product p : pList) {
					num++;
					if(num>=1000) break;
					logger.info("product:" + p.getItemCode()+" "+p.getProductName());
					extractCollector.regulateProduct(p);
				}
			}
			/*	List<Product> pList=new ArrayList<Product>();
			Product p1=new Product();
			p1.setItemCode(1L);
			p1.setProductName("K-touch C986T test name");
			p1.setShortDescription("a b c");
			Product p2=new Product();
			p2.setItemCode(2L);
			p2.setProductName("uleFone PC-2  test name");
			p2.setShortDescription("a b c");
			pList.add(p1);
			pList.add(p2);
			for (Product p : pList) {
				extractCollector.regulateProduct(p);
			}*/	
			Map<String,Map<String,String>> outMap=extractCollector.getOutMap();
			System.out.println("outMap:" + outMap);
			logger.info("outMap:" + outMap);
			
			
			
			StringBuffer sb=new StringBuffer();
			 Iterator<String>   iterator =outMap.keySet().iterator();
			 while(iterator.hasNext()){
				 String key=iterator.next();
				 sb.append(key).append("\n");
				 int attrNum=0;
				 Map<String,String> value=outMap.get(key);
				 //对value按长度降序排序
				 Set<Map.Entry<String, String>> set = value.entrySet();
					List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(set);
					Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
						public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
							if (o1.getValue().length() >= o2.getValue().length()) {
								return -1;
							} else {
								return 1;
							}
						}
					});
				for(Map.Entry<String, String> entry:list){
					 String key2=entry.getKey();
					 String value2=entry.getValue();
					 int len=value2.split(",").length;
					 attrNum+=len;
					 sb.append(key2).append("(").append(len).append(")").append(" : ").append(value2).append("\n");
				}
				
				 sb.append(key).append(" have ").append(attrNum).append(" itemcode ").append("\n");
				 sb.append("---------------------------\n");
			 }
			 try {
				FileUtils.writeStringToFile(file, sb.toString());
			} catch (IOException e) {
				logger.error("生成属性值推荐文件异常："+file.getAbsolutePath()+e.getMessage());
				e.printStackTrace();
			}
			long endTime=System.currentTimeMillis();
			long useTime=startTime-endTime;
			System.out.println("use time"+useTime+"毫秒");
	}
		

}
